<template>
  <div class="orders-container">
    <h2>我的订单</h2>

    <div v-if="loading" class="loading">
      加载中...
    </div>

    <div v-else-if="orders.length === 0" class="empty-orders">
      <i class="fas fa-box-open"></i>
      <p>暂无订单</p>
      <router-link to="/mall" class="go-shopping">
        去购物
      </router-link>
    </div>

    <template v-else>
      <!-- 订单列表 -->
      <div class="orders-list">
        <div v-for="order in orders" :key="order._id" class="order-card">
          <div class="order-header">
            <div class="order-info">
              <span class="order-id">订单号: {{ order._id }}</span>
              <span class="order-date">{{ formatDate(order.createdAt) }}</span>
            </div>
            <div class="order-status" :class="order.status">
              {{ getStatusText(order.status) }}
            </div>
          </div>

          <div class="order-items">
            <div v-for="item in order.items" :key="item.product._id" class="order-item">
              <img :src="item.product.images[0]" :alt="item.product.name">
              <div class="item-info">
                <router-link 
                  :to="`/mall/product/${item.product._id}`"
                  class="item-name"
                >
                  {{ item.product.name }}
                </router-link>
                <p class="item-price">
                  ¥{{ item.price }} × {{ item.quantity }}
                </p>
              </div>
            </div>
          </div>

          <div class="order-footer">
            <div class="order-total">
              <span>共 {{ getTotalItems(order) }} 件商品</span>
              <span class="total-amount">
                实付款: ¥{{ order.totalAmount.toFixed(2) }}
              </span>
            </div>

            <div class="order-actions">
              <router-link 
                :to="`/mall/orders/${order._id}`"
                class="view-detail"
              >
                查看详情
              </router-link>
              <button 
                v-if="order.status === 'pending'"
                class="cancel-order"
                @click="handleCancel(order._id)"
              >
                取消订单
              </button>
              <button 
                v-if="order.status === 'shipped'"
                class="confirm-receipt"
                @click="handleConfirmReceipt(order._id)"
              >
                确认收货
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <button 
          :disabled="currentPage === 1"
          @click="handlePageChange(currentPage - 1)"
        >
          上一页
        </button>
        <span>{{ currentPage }} / {{ totalPages }}</span>
        <button 
          :disabled="currentPage === totalPages"
          @click="handlePageChange(currentPage + 1)"
        >
          下一页
        </button>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { Order } from '@/types'
import api from '@/api/auth'

// 状态
const orders = ref<Order[]>([])
const loading = ref(false)
const currentPage = ref(1)
const totalPages = ref(1)

// 获取订单列表
const fetchOrders = async (page = 1) => {
  try {
    loading.value = true
    const response = await api.get('/orders/my-orders', {
      params: { page, limit: 10 }
    })
    orders.value = response.orders
    totalPages.value = response.totalPages
    currentPage.value = page
  } catch (error) {
    console.error('Failed to fetch orders:', error)
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    delivered: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 计算订单商品总数
const getTotalItems = (order: Order) => {
  return order.items.reduce((sum, item) => sum + item.quantity, 0)
}

// 取消订单
const handleCancel = async (orderId: string) => {
  if (!confirm('确定要取消这个订单吗？')) return

  try {
    await api.post(`/orders/${orderId}/cancel`)
    // 刷新订单列表
    fetchOrders(currentPage.value)
  } catch (error) {
    console.error('Failed to cancel order:', error)
    alert('取消订单失败，请重试')
  }
}

// 确认收货
const handleConfirmReceipt = async (orderId: string) => {
  if (!confirm('确认已收到商品吗？')) return

  try {
    await api.patch(`/orders/${orderId}/status`, { status: 'delivered' })
    // 刷新订单列表
    fetchOrders(currentPage.value)
  } catch (error) {
    console.error('Failed to confirm receipt:', error)
    alert('确认收货失败，请重试')
  }
}

// 分页
const handlePageChange = (page: number) => {
  fetchOrders(page)
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders-container {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

.loading,
.empty-orders {
  text-align: center;
  padding: 4rem 0;
  color: #666;
}

.empty-orders i {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.go-shopping {
  display: inline-block;
  margin-top: 1rem;
  padding: 0.5rem 2rem;
  background-color: #007bff;
  color: white;
  text-decoration: none;
  border-radius: 4px;
}

.order-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 1.5rem;
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background-color: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.order-info {
  display: flex;
  gap: 2rem;
  color: #666;
}

.order-status {
  font-weight: bold;
}

.order-status.pending { color: #ffc107; }
.order-status.paid { color: #17a2b8; }
.order-status.shipped { color: #007bff; }
.order-status.delivered { color: #28a745; }
.order-status.cancelled { color: #dc3545; }

.order-items {
  padding: 1rem;
}

.order-item {
  display: flex;
  gap: 1rem;
  padding: 0.5rem 0;
}

.order-item:not(:last-child) {
  border-bottom: 1px solid #eee;
}

.order-item img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-name {
  color: #333;
  text-decoration: none;
  font-weight: 500;
}

.item-price {
  color: #666;
  margin-top: 0.5rem;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background-color: #f8f9fa;
  border-top: 1px solid #eee;
}

.total-amount {
  margin-left: 1rem;
  color: #ff4444;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 1rem;
}

.order-actions button,
.order-actions a {
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  text-decoration: none;
}

.view-detail {
  background-color: #6c757d;
  color: white;
}

.cancel-order {
  background-color: white;
  border: 1px solid #dc3545;
  color: #dc3545;
}

.confirm-receipt {
  background-color: #28a745;
  color: white;
  border: none;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  margin-top: 2rem;
}

.pagination button {
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  cursor: pointer;
}

.pagination button:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}
</style> 